package com.yinwq.shorturl.service.impl;

import com.centit.support.network.UrlOptUtils;
import com.yinwq.shorturl.config.ShortConfig;
import com.yinwq.shorturl.entity.ShortRecord;
import com.yinwq.shorturl.mapper.ShortRecordMapper;
import com.yinwq.shorturl.service.ShortService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: yinwenqiang@qccr.com
 * @date: Created in 2019/10/28 20:18
 */
@Service
public class ShortServiceImpl implements ShortService {

    @Resource
    private ShortRecordMapper shortRecordMapper;

    @Resource
    private ShortConfig shortConfig;

    @Override
    public String generateShorUrl(String longUrl) {
        String shortUrlCode = null;
        StringBuffer sb = new StringBuffer();
        ShortRecord shortRecordReq = new ShortRecord();
        shortRecordReq.setLongUrl(longUrl);
        List<ShortRecord> shortRecords = shortRecordMapper.queryShortRecordListByWhere(shortRecordReq);
        if(CollectionUtils.isNotEmpty(shortRecords)){
            shortUrlCode = shortRecords.get(0).getShortUrlCode();
        }else {
            shortUrlCode = UrlOptUtils.shortenCodeUrl(longUrl, 6);
            ShortRecord shortRecord = new ShortRecord();
            shortRecord.setLongUrl(longUrl);
            shortRecord.setShortUrlCode(shortUrlCode);
            shortRecordMapper.insertShortRecord(shortRecord);
        }

        return sb.append(shortConfig.getShortUrlHost()).append("/").append(shortUrlCode).toString();
    }

    @Override
    public String queryLongUrl(String shortUrlCode) {
        ShortRecord shortRecordReq = new ShortRecord();
        shortRecordReq.setShortUrlCode(shortUrlCode);
        List<ShortRecord> shortRecords = shortRecordMapper.queryShortRecordListByWhere(shortRecordReq);
        if(CollectionUtils.isNotEmpty(shortRecords)){
            String longUrl = shortRecords.get(0).getLongUrl();
            return longUrl;
        }
        return null;
    }

}
